package com.geek.netty.demo.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @program netty-server
 * @description: nio
 * @author: chanzhugang
 * @create: 2021/08/16 15:38
 */
public class NIOServer extends Thread {


    /**
     * NIO 多路复用
     */
    @Override
    public void run() {
        // Selector: 类似调度员
        try (Selector selector = Selector.open();
             ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.bind(new InetSocketAddress(InetAddress.getLocalHost(), 8081));
            serverSocketChannel.configureBlocking(false);
            // channel 注册到selector，
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                // 单线程轮询机制，高效定位有效channel
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    sayHello((ServerSocketChannel) selectionKey.channel());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sayHello(ServerSocketChannel serverSocketChannel) {
        try (SocketChannel client = serverSocketChannel.accept();) {
            client.write(Charset.defaultCharset().encode("hello,多路复用的IO"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}